﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace WebUI.EditPages
{
    public partial class EditBrandName : BasePage
    {
        Brands brand;
        int brandID;
        string mode;

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if(Request.QueryString[KEY] == null)
            {
                CloseDlg(0);
                return;
            }

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            brand = (Brands)Session[Request.QueryString[KEY]];
            string oldFilter = brand.Filter;

            brandID = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode != ADD_MODE)
                brand.Filter = Brands.ColumnNames.ID + "=" + brandID.ToString();
            else
                btnSave.Enabled = false;

            if (!IsPostBack && brand.RowCount > 0 && mode != ADD_MODE)
                editBrand.BrandName = brand.BrandName;

            brand.Filter = oldFilter;
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            if (brand != null)
            {
                Save();
            }
        }

        private void Save()
        {
            string oldFilter = brand.Filter;
            if (mode == ADD_MODE)
            {
                brand.AddNew();
                brand.Deleted = false;
                brand.BranchID = Branches.CurrentBranchID;
            }
            else
            {
                brand.Filter = Brands.ColumnNames.ID + "=" + brandID;
            }
            brand.BrandName = editBrand.BrandName;
            brand.LastModifiedByUser = SessionUser.ID;
            brand.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);

            brand.Save();
            if (mode == ADD_MODE)
            {
                brand.StockKey = brand.ID;
                brand.Save();
            }
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true); 
            brand.Filter = oldFilter;
            ((Popup)Master).ShowMessage("Saved");
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (brand != null)
            {
                Save();
                CloseDlg(1);
            }
        }
    }
}
